package org.mcflier.appuntamento.tasks;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Set;

import javax.net.ssl.HttpsURLConnection;

import org.mcflier.appuntamento.core.Factory;
import org.mcflier.appuntamento.core.exception.ModulesException;
import org.mcflier.appuntamento.io.driver.db.JDBCDriver;
import org.mcflier.appuntamento.io.exception.JDBCConnectionException;
import org.mcflier.appuntamento.io.exception.JDBCStatementException;

public class DBMaintenanceTask extends AbstractTask {

	private JDBCDriver jdbc;

	public DBMaintenanceTask(String name, long delay) throws ModulesException {
		super(name, delay);

		Factory factory = Factory.getInstance();
		this.jdbc = (JDBCDriver)factory.getModuleInstance(Factory.MODULE_JDBC);
	}

	@Override
	public void doSomething() {
		Set<String> keys = this.arguments.keySet();

		for (String key : keys) {
			try {
				URL url = new URL(this.getArgument(key));
				String content="";
				HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
				con.addRequestProperty("User-Agent", "Appuntamento; "+System.getProperty("os.name")+" "+System.getProperty("os.version")+")");

				BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
				String inputLine;
				while ((inputLine = reader.readLine()) != null){
					content+=(inputLine+"\n");
				}
				reader.close();

				String[] lines = content.split(";");
				int updates = 0;
				for (int i = 0; i < lines.length; i++) {
					try {
						updates = this.jdbc.executeUpdate(lines[i]);
					} catch (JDBCConnectionException e) {
						this.logger.warning("Error executing query: "+lines[i]+"\n"+e.getMessage());
					} catch (JDBCStatementException e) {
						this.logger.warning("Error executing query: "+lines[i]+"\n"+e.getMessage());
					}
				}
				this.logger.fine("Maintenance task: "+key+" has updated "+updates+" row(s)");
			} catch (MalformedURLException e) {
				this.logger.warning("Error retrieving url maintenance file. Url may be corrupt: "+key);
			} catch (IOException e) {
				this.logger.warning("Error reading maintenance db file: "+e.getMessage());
			}
		}
	}
}